#include <ncurses.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#define DELAY 100000

int main() {
    int x, y, maxX, maxY;
    int direction = KEY_RIGHT;
    int snakeLength = 5;
    int snakeX[100], snakeY[100];
    int foodX, foodY;
    int score = 0;
    int gameOver = 0;

    // 初始化ncurses库
    initscr();
    noecho();
    curs_set(0);
    keypad(stdscr, TRUE);
    timeout(0);

    // 获取终端窗口的大小
    getmaxyx(stdscr, maxY, maxX);

    // 初始化蛇的初始位置和长度
    x = maxX / 2;
    y = maxY / 2;
    for (int i = 0; i < snakeLength; i++) {
        snakeX[i] = x - i;
        snakeY[i] = y;
    }

    // 生成食物的初始位置
    srand(time(NULL));
    foodX = rand() % (maxX-2)+1;
    foodY = rand() % (maxY-2)+1;

    // 游戏循环
    while (!gameOver) {
        clear();
        //绘制边界
        for(int i=0; i<=maxX; ++i)
        {
          mvprintw(0, i, "_");
          mvprintw(maxY-1, i, "^");
        }


        for(int j=0; j<=maxY; ++j)
        {
          mvprintw(j, 0, "|");
          mvprintw(j, maxX-1, "|");
        }

        // 显示分数
        mvprintw(1, 1, "Score: %d", score);

        // 绘制蛇
        for (int i = 0; i < snakeLength; i++) {
            mvprintw(snakeY[i], snakeX[i], "O");
        }

        // 绘制食物
        mvprintw(foodY, foodX, "*");

        // 移动蛇的位置
        int nextX = snakeX[0];
        int nextY = snakeY[0];
        switch (direction) {
            case KEY_UP:
                nextY--;
                break;
            case KEY_DOWN:
                nextY++;
                break;
            case KEY_LEFT:
                nextX--;
                break;
            case KEY_RIGHT:
                nextX++;
                break;
        }

        // 检查是否吃到食物
        if (nextX == foodX && nextY == foodY) {
            score++;
            snakeLength++;
            foodX = rand() % (maxX-2)+1;
            foodY = rand() % (maxY-2)+1;
        } 

        // 移动蛇的身体
        for (int i = snakeLength - 1; i > 0; i--) {
            snakeX[i] = snakeX[i - 1];
            snakeY[i] = snakeY[i - 1];
        }

        // 更新蛇头位置
        snakeX[0] = nextX;
        snakeY[0] = nextY;

        // 检查游戏结束条件
        if (nextX <= 0 || nextX >= maxX-1 || nextY <= 0 || nextY >= maxY-1) {
            gameOver = 1;
        }
        for (int i = 1; i < snakeLength; i++) {
            if (snakeX[i] == nextX && snakeY[i] == nextY) {
                gameOver = 1;
            }
        }

        // 刷新屏幕
        refresh();

        // 延迟一段时间
        usleep(DELAY);
        
        // 获取用户输入
        int key = getch();
        switch (key) {
            case KEY_UP:
            case KEY_DOWN:
            case KEY_LEFT:
            case KEY_RIGHT:
                direction = key;
                break;
            case 'q':
                gameOver = 1;
                break;
        }
    }

    // 清理并退出ncurses库
    endwin();

    printf("Game Over! Your score: %d\n", score);

    return 0;
}
